package com.rs.controller;

import com.rs.config.BusinessException;
import com.rs.entity.Student;
import com.rs.entity.login.Menu;
import com.rs.entity.login.User;
import com.rs.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author dehang
 * @date 2019/6/1
 */
@Controller
public class LoginController {

    @Autowired
    private UserService userService;

    @RequestMapping("/login")
    public String getTestById() {
        return "login";
    }

    /**
     * 验证账号密码
     * @param username
     * @param password
     * @param httpSession
     * @return
     */
    @RequestMapping(value="/dologin",method = RequestMethod.POST)
    @ResponseBody
    public Map dologin(String username, String password, HttpSession httpSession){
        Map result = new HashMap();
        User user = userService.login(username, password);
        if (user == null) {
            result.put("code", 1);
            result.put("msg", "账号或密码错误");
        } else {

                result.put("code", 0);
                httpSession.setAttribute("user",user);

        }
        return result;
    }

    /**
     * 从本系统登陆首页
     * @param httpSession
     * @param model
     * @return
     */
    @RequestMapping("/index")
    public String index(HttpSession httpSession, Model model){
        Object user1 = httpSession.getAttribute("user");
        if (user1 instanceof Student) {
//            throw new BusinessException("无权限");
            return "/login";
        }
        User user=(User)httpSession.getAttribute("user");
        model.addAttribute("nickName",user.getNickName());

        return "index";
    }

    @RequestMapping("/main")
    public String main(HttpSession httpSession, Model model){
        Object user1 = httpSession.getAttribute("user");
        if (user1 instanceof Student) {
//            throw new BusinessException("无权限");
            return "/login";
        }
        User user=(User)httpSession.getAttribute("user");
        model.addAttribute("user",user);
        return "index/main";
    }


    @RequestMapping("/redirect")
    public String redirect(HttpServletRequest request, HttpServletResponse response) throws Exception{
        //清理本地session
        request.getSession().removeAttribute("user");
        //重定向登陆页
        return "redirect:/login";
    }

}
